<template>
  <view class="page-bgi">
    <!-- 放入头部组件 -->
    <navbar title="账号信息"></navbar>
    <view class="information">
      <!-- 头像 -->
      <view class="avatar">
        <text>头像</text>
        <image :src="userInfo.avatarUrl" mode="aspectFill" />
        <view class="changeAvatar" @click="changeAvatar">
          点击更换
        </view>
      </view>
      <!-- 昵称 -->
      <view class="component">
        <text>昵称</text>
        <u-input class="input" v-model="userInfo.nickName" type="text" />
      </view>
      <!-- 性别选择区域 -->
      <view class="component1" @click="openGenderActionSheet">
        <text>性别</text>
        <u-input class="input" v-model="userInfo.genderText" type="text" placeholder="请选择性别" readonly>
          <!-- 使用suffix插槽将图片嵌入输入框内部 -->
          <template #suffix>
            <image src="@/static/最新政策详情ico.png" class="gender-icon"></image>
          </template>
        </u-input>
      </view>
      <!-- 出生日期 -->
      <view class="component1">
        <text>出生日期</text>
        <picker mode="date" :value="userInfo.birthday" @change="handleDateChange" start="1900-01-01" :end="today">
          <u-input class="input" v-model="userInfo.birthday" type="text" placeholder="请选择出生日期" readonly>
            <!-- 使用suffix插槽将图片嵌入输入框内部 -->
            <template #suffix>
              <image src="@/static/最新政策详情ico.png" class="gender-icon"></image>
            </template>
          </u-input>
        </picker>
      </view>
      <!-- 学历 -->
      <view class="component1" @click="showEducation = true">
        <text>学历</text>
        <u-input class="input" type="text" v-model="userInfo.educationText" placeholder="请选择学历" readonly>
          <!-- 使用suffix插槽将图片嵌入输入框内部 -->
          <template #suffix>
            <image src="@/static/最新政策详情ico.png" class="gender-icon"></image>
          </template>
        </u-input>
        <UPicker :show="showEducation" :columns="educationColumns" @confirm="confirmEducation"
          @cancel="showEducation = false" title="选择学历">
        </UPicker>
      </view>
      <!-- 职业 -->
      <view class="component1" @click="showEmployment = true">
        <text>职业</text>
        <u-input class="input" type="text" v-model="userInfo.employmentText" placeholder="请选择职业" readonly>
          <!-- 使用suffix插槽将图片嵌入输入框内部 -->
          <template #suffix>
            <image src="@/static/最新政策详情ico.png" class="gender-icon"></image>
          </template>
        </u-input>
        <UPicker :show="showEmployment" :columns="employmentColumns" @confirm="confirmEmployment"
          @cancel="showEmployment = false" title="选择事业">
        </UPicker>
      </view>
      <!-- 所在地 -->
      <view class=" component1">
        <text>所在地</text>
        <u-input class="input" v-model="userInfo.location" type="text" />
      </view>
    </view>
    <!-- bottom 底部固定 -->
    <view class="bottom">
      <button @click="back">
        <text>返回</text>
      </button>
      <button class="confirm" @click="submitUserInfo">
        <text>确认修改</text>
      </button>
    </view>
  </view>
</template>

<script setup>
  import navbar from '@/components/navbar/navbar.vue'
  import {
    ref,
    reactive
  } from 'vue'
  import {
    onLoad
  } from '@dcloudio/uni-app'
  import {
    getUser,
    updateUser
  } from '@/api/person.js'
  import UPicker from '@/uni_modules/uview-plus/components/u-picker/u-picker.vue'
  const today = ref('')

  const userInfo = ref({
    nickName: '',
    avatarUrl: '/static/defaultAvatar.png',
    gender: 0,
    genderText: '',
    birthday: '',
    location: '',
    employmentStatus: 0,
    employmentText: '',
    education: 0,
    educationText: ''
  })

  const showEducation = ref(false);
  const educationDict = [{
      key: 1,
      name: '小学'
    },
    {
      key: 2,
      name: '初中'
    },
    {
      key: 3,
      name: '高中'
    },
    {
      key: 4,
      name: '大专'
    },
    {
      key: 5,
      name: '本科'
    },
    {
      key: 6,
      name: '硕士'
    },
    {
      key: 7,
      name: '博士'
    }
  ];
  const educationOptions = ref(educationDict);
  const educationColumns = ref([
    educationDict.map(item => item.name)
  ]);
  const confirmEducation = (e) => {
    const selectedName = e.value[0];
    const selected = educationOptions.value.find(item => item.name === selectedName);
    if (selected) {
      userInfo.value.educationText = selected.name;
      userInfo.value.education = selected.key;
    }
    showEducation.value = false;
  };
  const showEmployment = ref(false)
  const employmentDict = [{
      key: 1,
      name: '在岗'
    },
    {
      key: 2,
      name: '待岗'
    },
    {
      key: 3,
      name: '离职'
    },
    {
      key: 4,
      name: '实习'
    },
    {
      key: 5,
      name: '兼职'
    }
  ];
  const employmentOptions = ref(employmentDict);
  const employmentColumns = ref([
    employmentDict.map(item => item.name)
  ]);
  const confirmEmployment = (e) => {
    const selectedName = e.value[0];
    const selected = employmentOptions.value.find(item => item.name === selectedName);
    if (selected) {
      userInfo.value.employmentText = selected.name;
      userInfo.value.employmentStatus = selected.key;
    }
    showEmployment.value = false;
  };

  onLoad(() => {
    initToday();
    getUser().then((res) => {
      console.log(res)
      if (res.code === 200) {
        userInfo.value.nickName = res.data.nikeName
        if (res.data.avatar) {
          userInfo.value.avatarUrl = res.data.avatar
        }
        userInfo.value.gender = res.data.gender || 0
        userInfo.value.genderText = getGenderText(res.data.gender)
        userInfo.value.birthday = res.data.birthday
        userInfo.value.location = res.data.location
        const educationKey = Number(res.data.education) || 0;
        const matchedEducation = educationDict.find(item => item.key === educationKey);
        userInfo.value.educationText = matchedEducation ? matchedEducation.name : '';
        userInfo.value.education = educationKey;
        const employmentKey = Number(res.data.employmentStatus) || 0;
        const matchedEmployment = employmentDict.find(item => item.key === employmentKey);
        userInfo.value.employmentText = matchedEmployment ? matchedEmployment.name : '';
        userInfo.value.employmentStatus = employmentKey;
      }
    })
  })
  const changeAvatar = () => {
    uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera']
    }).then(res => {
      const tempFilePath = res.tempFilePaths[0]
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: 'http://localhost:8081/wechat/user/avatar',
          filePath: tempFilePath,
          name: 'file',
          header: {
            'Authorization': `Bearer ${uni.getStorageSync('token')}`
          },
          success: (uploadRes) => {
            if (uploadRes.statusCode === 200) {
              const data = JSON.parse(uploadRes.data);
              userInfo.value.avatarUrl = data.url
            }
          }
        })
      })
    })
  }

  const getGenderText = (value) => {
    const map = {
      1: '男',
      2: '女',
      0: '未知'
    };
    return map[value] || '';
  };

  const openGenderActionSheet = () => {
    uni.showActionSheet({
      itemList: ['男', '女'],
      success: (res) => {
        const genderMap = [{
            text: '男',
            value: 1
          },
          {
            text: '女',
            value: 2
          }
        ];
        userInfo.value.genderText = genderMap[res.tapIndex].text;
        userInfo.value.gender = genderMap[res.tapIndex].value;
      }
    });
  };

  const initToday = () => {
    const date = new Date();
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    today.value = `${year}-${month}-${day}`;
  };

  const handleDateChange = (e) => {
    userInfo.value.birthday = e.detail.value;
  };

  const submitUserInfo = async () => {
    const userData = {
      nikeName: userInfo.value.nickName,
      avatar: userInfo.value.avatarUrl,
      birthday: userInfo.value.birthday,
      education: userInfo.value.education,
      employmentStatus: userInfo.value.employmentStatus,
      location: userInfo.value.location,
      gender: userInfo.value.gender
    }
    updateUser(userData).then(res => {
      if (res.code === 200) {
        uni.showToast({
          title: '修改成功',
          icon: 'success'
        })
      } else {
        uni.showToast({
          title: '提交失败',
          icon: 'error'
        })
      }
    })
  }

  const back = () => {
    uni.navigateBack();
  }
</script>

<style lang="scss" scoped>
  .header {
    color: #fff;
    font-size: 36rpx;
  }

  :deep(.right-content) {
    margin-right: 75rpx;
  }

  .page-bgi {
    margin-top: 30rpx;
    padding-bottom: 98rpx;
    box-sizing: border-box;
    min-height: 100vh;
    background-image: url('@/static/对话背景ico.png');
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
  }

  .information {
    margin: 30rpx;
    padding: 30rpx;
    // height: 100vh;
    box-sizing: border-box;
    background-color: #fffefe;
    overflow: visible !important;
  }

  .information text {
    font-family: Source Han Sans CN;
    font-size: 30rpx;
    font-weight: normal;
    font-stretch: normal;
    letter-spacing: 0rpx;
    color: #333333;
  }

  .information .avatar {
    position: relative;
    width: 128rpx;
    height: 194rpx;
    box-sizing: border-box;
    overflow: hidden;
  }

  .information .avatar image {
    display: block;
    margin-top: 24rpx;
    border-radius: 15%;
    width: 128rpx;
    height: 128rpx;
  }

  .information .avatar .changeAvatar {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 128rpx;
    height: 42rpx;
    background-color: #333333;
    border-radius: 16rpx;
    opacity: 0.5;
    text-align: center;
    font-size: 22rpx;
    line-height: 45rpx;
    letter-spacing: 0rpx;
    color: #ffffff;
  }

  .information .component {
    margin-top: 48rpx;
    height: 168rpx;
    font-family: Source Han Sans CN;
    font-weight: normal;
    font-stretch: normal;
    letter-spacing: 0rpx;

    text {
      height: 30rpx;
      font-size: 30rpx;
      line-height: 45rpx;
      color: #333333;
    }

    ::v-deep .u-input {
      pointer-events: auto !important;
      margin-top: 24rpx;
      height: 90rpx;
      background-color: #f7f7f7 !important;

      ::v-deep .u-input__input {
        padding: 31rpx 0 31rpx 24rpx;
        height: 90rpx !important;
        font-size: 28rpx !important;
        color: #9ca3af !important;
        line-height: 45rpx !important;
      }
    }
  }

  .information .component1 {
    margin-top: 48rpx;
    min-height: 168rpx;
    font-family: Source Han Sans CN;
    font-weight: normal;
    font-stretch: normal;
    letter-spacing: 0rpx;

    text {
      height: 30rpx;
      font-size: 30rpx;
      line-height: 45rpx;
      color: #333333;
    }

    ::v-deep .u-input {
      margin-top: 24rpx;
      height: 90rpx;
      background-color: #f7f7f7 !important;

      ::v-deep .u-input__input {
        padding: 31rpx 0 31rpx 24rpx;
        height: 90rpx !important;
        font-size: 28rpx !important;
        color: #9ca3af !important;
        line-height: 45rpx !important;
      }
    }

    /* 添加性别图标样式 */
    .gender-icon {
      width: 14rpx;
      /* 特定宽度 */
      height: 26rpx;
      /* 特定高度 */
      margin-right: 16rpx;
      /* 与输入框右侧保持距离 */
    }

    /* 调整输入框内边距，防止文字被图标遮挡 */
    ::v-deep .u-input__input {
      padding-right: 25rpx !important;
      /* 增加右侧内边距 */
    }
  }

  .bottom {
    z-index: 999;
    display: flex;
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 98rpx;
    background-color: #ffffff;
    box-shadow: 0rpx -2rpx 4rpx 0rpx rgba(189, 189, 189, 0.36);
    border: solid 1rpx #ffffff;
  }

  .bottom button {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 17rpx 30rpx;
    width: 337rpx;
    height: 64rpx;
    background-color: #f7f7f7;
    border-radius: 16rpx;
    border: none;
  }

  .bottom button::after {
    border: none; // 取消伪元素生成的边框
  }

  .bottom button text {
    font-family: Source Han Sans CN;
    font-size: 28rpx;
    font-weight: normal;
    font-stretch: normal;
    letter-spacing: 0rpx;
    color: #9ca3af;
  }

  .bottom button:hover {
    background-color: #e1383c;
  }

  .bottom button:hover text {
    color: #ffffff;
  }

  .radio-group {
    margin-top: 24rpx;
    display: flex;
  }

  .radio-item {
    margin-right: 40rpx;
    font-size: 28rpx;
  }

  /* 添加调试样式确保输入框可点击 */
  .component1 .input {
    pointer-events: auto !important;
    z-index: 10;
  }
</style>